package com.bluedon.ism.sensitive;


import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Service("sensitiveService")
public class SensitiveServiceBean implements SensitiveService{
	private static final Logger logger=LoggerFactory.getLogger(SensitiveServiceBean.class);
	private static SensitiveBuilder builder=new SensitiveBuilder();
	
	private String replaceString ="";
	private String configPath = "sensitive_word.txt";
	private DataSource dataSource;
	
	@Override
	public String replace(String content) {
		if(StringUtils.isNotBlank(content))
				content = content.trim();
		content = Validator.filter(content);
		if(replaceString==null)
			return content;
		Matcher matcher=builder.getMatcher(content);
		return matcher.replace(replaceString);
	}

	public void setReplaceString(String replaceString) {
		this.replaceString = replaceString;
	}

	public void setConfigPath(String configPath) {
		this.configPath = configPath;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	@PostConstruct
	public void initialize() {
		if(logger.isInfoEnabled())
			logger.info("initializing SensitiveServiceBean");
		Assert.notNull(replaceString, "必须设置敏感词的替换关键词");
		BufferedReader reader = null;
		if(configPath!=null) {
			try {
				InputStream in = SensitiveServiceBean.class.getClassLoader().getResourceAsStream(configPath);
				if (in == null) {
			            in = SensitiveServiceBean.class.getResourceAsStream(configPath);
			    }
				reader=new BufferedReader(new InputStreamReader(in));
				List<String> keywords=new ArrayList<String>();
				String line;
				while((line=reader.readLine())!=null) {
					keywords.add(line);
				}
				builder.setKeywords(keywords);
				logger.info("------------------------senstive load success, senstive wrold:"+keywords);
			} catch (FileNotFoundException e) {
				logger.error("configPath file doesn't exists",e);
			} catch (IOException e) {
				logger.error("configPath file read error",e);
			} finally {
				try {
					if(reader != null)
						reader.close();
				} catch (IOException e) {
					logger.error("configPath file colse error",e);
				}
			}
		}
		if(dataSource!=null) {
			try {
				Connection conn=dataSource.getConnection();
				PreparedStatement ps=conn.prepareStatement("select * from sensitive_word");
				ResultSet rs=ps.executeQuery();
				List<String> keywords=new ArrayList<String>();
				while(rs.next()) {
					String word=rs.getString("word");
					if(word!=null) {
						keywords.add(word);
					}
				}
				rs.close();
				ps.close();
				conn.close();
				builder.setKeywords(keywords);
			} catch (SQLException e) {
				logger.error("db access failed", e);
			}
		}
		if(logger.isInfoEnabled())
			logger.info("initialized SensitiveServiceBean");
	}
	
	//~ InitializingBean implement=============================================

}
